package com.vay.de.dang.online.ui.apply;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.URLSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.vay.de.dang.online.VnApp;
import com.vay.de.dang.online.resp.RCollectionAccountDto;
import com.vay.de.dang.online.view.DialogConfirm;
import com.vay.de.dang.online.view.LoanAmountSelector;
import com.vay.de.dang.online.web.BaseApi;
import com.vay.de.dang.online.web.LoanApi;
import com.vay.de.dang.online.web.ReqResult;
import com.vay.de.dang.online.R;
import com.vay.de.dang.online.databinding.ActivityLoanConfirmBinding;
import com.vay.de.dang.online.entiy.AppConfigEntity;
import com.vay.de.dang.online.entiy.CommodityEntity;
import com.vay.de.dang.online.entiy.CustomerEntity;
import com.vay.de.dang.online.resp.RCodeTableDto;
import com.vay.de.dang.online.resp.RExchangePlanDto;
import com.vay.de.dang.online.resp.RExchangePlanItemDto;
import com.vay.de.dang.online.resp.RFinancialProductDto;
import com.vay.de.dang.online.ui.WithBack1Activity;
import com.vay.de.dang.online.ui.HomeActivity;
import com.vay.de.dang.online.util.CallerUtil;
import com.vay.de.dang.online.util.ClickURLSpan;
import com.vay.de.dang.online.util.RequestHelper;
import com.vay.de.dang.online.util.VnContext;
import com.vay.de.dang.online.util.VnDefine;
import com.vay.de.dang.online.util.VnUIManager;
import com.vay.de.dang.online.util.VnUtil;
import com.vay.de.dang.online.view.DialogOk;
import com.vay.de.dang.online.web.LoginApi;
import com.vay.de.dang.online.web.ReqCallback;

import java.util.ArrayList;
import java.util.List;

import cc.taylorzhang.singleclick.SingleClickUtil;

/**
 * 贷款确认页面
 */
public class ConfirmLoanActivity extends WithBack1Activity {

    private ActivityLoanConfirmBinding binding;

    private String commodityNum;
    private List<RFinancialProductDto> productList = new ArrayList<>();
    private RFinancialProductDto currentProduct;
    private TextView productMoney;
    private LinearLayout dayLayout;
    private LoanAmountSelector amountChoice;

    private List<TextView> viewsDto = new ArrayList<>();

    private RCollectionAccountDto cAccountDto;
    private RExchangePlanDto exchangePlanDto;

    private AppConfigEntity appConfig;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoanConfirmBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        String html = getString(R.string.lc_tips_5)
                + "<a href=\"" + VnDefine.CreditPolicyUrl + "\"><font color=\"#FF0000\">" + getString(R.string.lc_tips_6_credit) + "</font></a>";
        binding.creditLabel.setText(Html.fromHtml(html));
        binding.creditLabel.setMovementMethod(LinkMovementMethod.getInstance());

        // 业务埋点
        BaseApi.execBuriedPoint(8000, 8000, "确认借款", "确认借款页面可见");

        SingleClickUtil.onSingleClick(binding.bntBack, view -> {
            // 业务埋点
            BaseApi.execBuriedPoint(8010, 8000, "确认借款", "确认借款返回");
            finish();
        });

        SingleClickUtil.onSingleClick(binding.bntService, view -> {

            LoginApi.queryServicePhone(new ReqCallback(mActivity) {
                @Override
                public void callback(ReqResult value) {
                    if (value.isOk()) {
                        CustomerEntity customer = (CustomerEntity) value.result;
                        new DialogConfirm(mActivity)
                                .setTitleText(R.string.login_service_title)
                                .setHintText(R.string.login_service_hint)
                                .setContentText(customer.getCustomerTelephone() + "\n" + customer.getCustomerEmail())
                                .showConfirm(() -> {
                                    CallerUtil.call(mActivity, value.msg);
                                });
                    }
                }
            }.showDialog(true));
        });

        commodityNum = RequestHelper.currentCommodityNum;
        if (VnUtil.isEmpty(RequestHelper.products)) {
            showHint("Data Error");
            finish();
            return;
        }

        productList.clear();
        productList.addAll(RequestHelper.products);

        // 首贷，修改收款
        appConfig = VnContext.instance().getAppConfig();

        // 查询收款方式
        queryAccount();

        // 是否送审核手机号
//        if (config.isGpPhone()) {
//            binding.daysLayout.setVisibility(View.VISIBLE);
//            binding.loanDays.setText(productDto.getFinancialProductsTerm() + " " + getString(R.string.label_days));
//        }

        if (productList.size() > 1) {
            loadMoreProduct();
        } else {
            loadOneProduct();
        }

        if (appConfig != null) {
            int state = appConfig.getUserState();
            // 1首贷 2复贷 3复贷资料过期
            if (state == 1 || (state == 2 && appConfig.getBankCardNumberOpen() == 1) || state == 3) {

                binding.receiveAccountLayout.bntModify.setVisibility(View.VISIBLE);
                binding.receiveAccountLayout.bntModify.setOnClickListener(v -> {
                    modifyAccount();
                });
            } else {
                binding.receiveAccountLayout.bntModify.setVisibility(View.GONE);
            }
        }
    }

    private void queryAccount() {
        LoanApi.queryCollectionAccount(new ReqCallback() {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    cAccountDto = (RCollectionAccountDto) value.result;
                    RCodeTableDto method = cAccountDto.getWithdrawalMethod();
                    RCodeTableDto type = cAccountDto.getWithdrawalType();
                    if (cAccountDto != null && method != null) {
                        if ("3".equals(type.getValue())) {
                            binding.receiveAccountLayout.getRoot().setVisibility(View.GONE);
                        } else {
                            binding.receiveAccountLayout.getRoot().setVisibility(View.VISIBLE);
                        }

                        showItemView(binding.receiveAccountLayout.getRoot(), getString(R.string.lc_label_2), cAccountDto.getBankCardNumber());
                    } else {
                        showHint("Collection Account Data is null");
                        finish();
                    }
                }
            }
        });
    }

    private void loadOneProduct() {
        binding.productLayout.removeAllViews();
        currentProduct = productList.get(0);
        View iv = getLayoutInflater().inflate(R.layout.view_money_1, null);
        productMoney = iv.findViewById(R.id.tv_money);
        binding.productLayout.addView(iv);

        queryExchangePlan();
    }

    private void loadMoreProduct() {
        binding.productLayout.removeAllViews();
        View iv = getLayoutInflater().inflate(R.layout.view_money_2, null);
        productMoney = iv.findViewById(R.id.p_money_tv);
        dayLayout = iv.findViewById(R.id.days_layout);
        amountChoice = iv.findViewById(R.id.money_bar);
        binding.productLayout.addView(iv);

        amountChoice.setOnCallback(list1 -> loadProduct(list1));
        amountChoice.loadLoanAmount(productList);
    }

    private void loadProduct(List<RFinancialProductDto> list) {
        if (list.isEmpty()) return;

        viewsDto.clear();
        dayLayout.removeAllViews();

        int sw = VnApp.getDimension(R.dimen.x72);
        int sh = VnApp.getDimension(R.dimen.x28);
        for (int index = 0; index < list.size(); index++) {
            RFinancialProductDto p = list.get(index);
            TextView tv = (TextView) getLayoutInflater().inflate(R.layout.view_day, null);
            tv.setTag(p);
            tv.setText(p.getFinancialProductsTerm() + " " + getString(R.string.label_days));
            tv.setBackgroundResource(R.drawable.bg_day_n);
            tv.setOnClickListener(view -> {
                currentProduct = p;
                updateProductDto();
                queryExchangePlan();
            });
            LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(sw, sh);
            lp2.leftMargin = index * VnApp.getDimension(R.dimen.x24);

            dayLayout.addView(tv, lp2);
            viewsDto.add(tv);
        }

        // 默认第一个
        currentProduct = list.get(0);
        productMoney.setText(VnUtil.toMoneyStr2(currentProduct.getFinancialProductsAmount()));
        updateProductDto();
        queryExchangePlan();
    }

    private void updateProductDto() {
        for (TextView tv : viewsDto) {
            RFinancialProductDto p = (RFinancialProductDto) tv.getTag();
            if (p == currentProduct) {
                tv.setBackgroundResource(R.drawable.bg_day_p);
                tv.setTextColor(Color.parseColor("#ffffff"));
            } else {
                tv.setBackgroundResource(R.drawable.bg_day_n);
                tv.setTextColor(Color.parseColor("#000000"));
            }
        }
    }

    private void queryExchangePlan() {
        // 查询还款计划
        LoanApi.queryExchangePlan(commodityNum,
                currentProduct.getFinancialProductsCode(),
                new ReqCallback(mActivity) {
                    @Override
                    public void callback(ReqResult value) {
                        if (value.isOk()) {
                            exchangePlanDto = (RExchangePlanDto) value.result;

                            Spannable cbText = (Spannable) binding.creditLabel.getText();
                            int end = cbText.length();
                            URLSpan[] urls = cbText.getSpans(0, end, URLSpan.class);
                            SpannableStringBuilder style = new SpannableStringBuilder(cbText);
                            style.clearSpans();
                            for (URLSpan url : urls) {
                                ClickURLSpan urlSpan = new ClickURLSpan(mActivity, url.getURL(), exchangePlanDto.getContractParams());
                                style.setSpan(urlSpan, cbText.getSpanStart(url), cbText.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }

                            binding.creditLabel.setText(style);
                            // 贷款金额
                            productMoney.setText(VnUtil.toMoneyStr1(exchangePlanDto.getLoanMoney()));

                            // 付款时间
                            showItemView(binding.fkTimeLayout.getRoot(), getString(R.string.lc_label_1), CallerUtil.currentTime());

                            // 到手金额
                            showItemView(binding.receiveMoneyLayout.getRoot(),
                                    getString(R.string.lc_label_3), VnUtil.toMoneyStr1(exchangePlanDto.getArrivalMoney()));
                            // 服务费
                            showItemView(binding.feesLayout.getRoot(),
                                    getString(R.string.lc_label_4), VnUtil.toMoneyStr1(exchangePlanDto.getComprehensiveServiceCharge()));

                            List<RExchangePlanItemDto> plan = exchangePlanDto.getExchangePlanList();
                            if (plan != null && plan.size() > 0) {

                                RExchangePlanItemDto planItem = plan.get(0);

                                // 应付时间
                                showItemView(binding.debtTimeLayout.getRoot(), getString(R.string.lc_label_5), planItem.getRepaymentDate());
                                // 应付金额
                                showItemView(binding.debtTotalLayout.getRoot(), getString(R.string.lc_label_6),
                                        VnUtil.toMoneyStr1(planItem.getRepaymentMoney()));
                            }

                            loadView();
                        }
                    }
                }.showDialog(true));
    }

    private void modifyAccount() {
        Intent intent = new Intent();
        intent.setClass(mActivity, AccountModifyActivity.class);
        intent.putExtra("obj", cAccountDto);
        startActivityForResult(intent, 5000);
    }

    private void loadView() {

        SingleClickUtil.onSingleClick(binding.bntSubmit, view -> {

            // 业务埋点
            BaseApi.execBuriedPoint(8099, 8000, "确认借款", "提交借款");

            if (!binding.credit.isBoxChecked()) {
                showHint(R.string.label_credit_agreement_warring);
                return;
            }

            LoanApi.reschedulingSubmission(commodityNum,
                    currentProduct.getFinancialProductsCode(), new ReqCallback(mActivity) {
                        @Override
                        public void callback(ReqResult value) {
                            if (value.isOk()) {
                                final String data = (String) value.result;

                                // 用户状态:1首贷 2复贷 3复贷资料过期
                                if (appConfig.getUserState() == 1) {
                                    VnApp.trackEventFirstOrder();
                                } else {
                                    VnApp.trackEventOrder();
                                }

                                new DialogOk(mActivity).showOk(() -> showOkDialog(data));
                            }
                        }
                    }.showDialog(true));
        });
    }

    private void showOkDialog(String value) {
        HomeActivity.reloadHome();
        if ("1".equals(value)) {
            LoanApi.queryRecommend(new ReqCallback(mActivity) {
                @Override
                public void callback(ReqResult value) {
                    VnUIManager.closeAll();

                    if (value.isOk()) {
                        List<CommodityEntity> list = (List<CommodityEntity>) value.result;
                        if (!VnUtil.isEmpty(list)) {
                            RecommendActivity.allData = list;
                            VnUIManager.nextActivity(mActivity, RecommendActivity.class);
                        } else {
                            showHint(VnApp.getStr(R.string.label_no_recommend));
                        }
                    }
                }
            }.showDialog(true));
            // 显示推荐
            // VnUIManager.nextActivity(mActivity, RecommendActivity.class);
        }
        // 回到首页
        else {
            VnUIManager.closeAll();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 5000) {
                queryAccount();
            }
        }
    }

    // 显示选项信息
    private void showItemView(View iv, String label, String content) {
        showItemView(iv, label, content, null, true);
    }

    private void showItemView(View iv, String label, String content, View.OnClickListener click, boolean showLine) {
        TextView tvLabel = iv.findViewById(R.id.tv_label);
        TextView tvContent = iv.findViewById(R.id.tv_content);
        ImageView bntModify = iv.findViewById(R.id.bnt_modify);
        View line = iv.findViewById(R.id.line);

        tvLabel.setText(label);
        tvContent.setText(content);

        if (click != null) {
            bntModify.setVisibility(View.VISIBLE);
        } else {
            bntModify.setVisibility(View.GONE);
        }

        line.setVisibility(showLine ? View.VISIBLE : View.INVISIBLE);
    }
}
